#! /usr/bin/python
# -*- coding: utf-8 -*-
#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
# DisplayImage display a fits image on ds9.
#_________________________________________________________
# A.Z. - 04/08 => Creation
#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
import numpy
import pyfits
import qviewF
import commands
import numdisplay
from os import path
from pylab import *
from subprocess import call
from globalVariables import gv
from matplotlib.widgets import Cursor
from dataFileReader import DataFileReader


class DisplayImage:
  __fits = None # List with the fits files
   
  def __init__(self, ifile):
    """
    Open the list file and read it
    """
    dfr = DataFileReader()
    F   = numpy.array( dfr.read(ifile) ).transpose()
    self.__fits = [ path.join(path.dirname(ifile), f) for f in F[0] ]  # 0==first column in the file



  def openDS9(self):
    """
    Open ds9 if it's not open
    """
    ds9pid = ( commands.getoutput('pidof ds9') ).split()
    if len(ds9pid)==0:
      try:
        r = call("ds9 &", shell=True)
        if r < 0: qvieF.Abort("ds9 was terminated by signal %s" % -r )
      except OSError, e: qviewF.Abort("Execution failed: %s" % e)

      raw_input( "Openig ds9. Press <return> when read." )



  def __call__(self,n, event=None ):
    """
    Display the image
    """

    self.openDS9() # Open ds9 if it's not open
    
    N = len( self.__fits )
    if n<0 or n>=N:
      qviewF.Abort("Wrong number (%d). Images go from %d to %d." % (n,0,N-1))
    print "Displaying image %s on ds9." % self.__fits[n]

    # I make a false key press to print the point information
    # I can do it by myself, but it's better to let 'control' do it!
    if event!=None:
      event.key="p"
      print "Point:  ", 
      qviewF.control(event)

    # Display
    im = pyfits.getdata( self.__fits[n] )
    numdisplay.display( im, zscale=True )
